<template>
  <div class="w">
    <!-- 标题 -->
    <div style="overflow: hidden">
      <div style="background-color:#ffd04b;width: 10px;height: 30px;float: left"></div>
      <div style="float: left;margin-left: 10px">
        <span style="color: #FFFFFF;font-size: 20px;font-weight: bold;">评论</span>
      </div>
    </div>

    <!-- 添加评论按钮 -->
    <div class="add-comment">
      <el-button type="primary" class="btn" @click="add">添加评论</el-button>
    </div>

    <!-- 添加评论弹窗 -->
    <el-dialog title="添加评论" draggable :before-close="cancel" v-model="addCommentVisible"
               style="width: 660px; padding: 40px; height: 340px; position: relative">
      <el-form>
        <el-form-item label="评分">
          <el-rate v-model="rating" :max="10.0" show-score allow-half text-color="#ff9900" score-template="{value}">
          </el-rate>
        </el-form-item>
        <el-form-item label="评论">
          <el-input
              v-model="saveFrom.comments"
              :autosize="{ minRows: 6, maxRows: 4 }"
              maxlength="200"
              show-word-limit
              type="textarea"
              placeholder="请输入评论信息"
          />
        </el-form-item>
      </el-form>
      <div style="position: absolute;bottom: 20px;right: 20px">
        <el-button type="info" @click="cancel">取消</el-button>
        <el-button type="primary" @click="addComment" :loading="loading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 评论列表 -->
    <el-card style="margin-top: 20px;background-color: #141d2c;border: #0f1827;border-radius: 10px">
      <div v-for="comment in paginatedData" :key="comment.id" class="comment-item">
        <div>
          <el-row>
            <el-col :span="2">
              <el-avatar style="width: 40px; height: 40px;" :src="comment.avatar ? BASE_URL + comment.avatar : defaultAvatar"/>
            </el-col>
            <el-col :span="10">
              <p>{{ comment.nickname }}</p>
            </el-col>
            <el-col :span="10">
              <p style="text-align: right">{{ comment.createTime }}</p>
            </el-col>
          </el-row>
          <div class="comment-content">{{ comment.content }}</div>
        </div>
      </div>
    </el-card>

    <!-- 分页组件 -->
    <el-card style="margin:10px 20px 0 20px;">
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="commentsData.length"
          @current-change="handlePageChange"
          style="margin-left: 35%;"
      />
    </el-card>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import qs from "qs";

const props = defineProps({
  filmId: {
    type: Number,
    required: true,
  },
  userId: {
    type: String,
    required: true,
  },
});


// 数据源
const commentsData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);

// 计算当前页数据
const paginatedData = computed(() => {
  const offset = (currentPage.value - 1) * pageSize.value;
  return commentsData.value.slice(offset, offset + pageSize.value);
});

// 分页变化处理
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
};

// 获取评论
const getComments = () => {
  const data = qs.stringify({ filmId: props.filmId });
  axios.get(BASE_URL + '/v1/comments/search?' + data)
      .then((response) => {
        if (response.data.code === 2000) {
          commentsData.value = response.data.data;
        } else {
          ElMessage.error(response.data.msg);
        }
      });
};

onMounted(() => {
  getComments();
});

// 控制弹窗
const addCommentVisible = ref(false);
const rating = ref(0); // 评分值
const saveFrom = ref({ comments: '' }); // 注意字段名统一为 comments
const loading = ref(false); // 防止重复提交

const add = () => {
  addCommentVisible.value = true;
};

const cancel = () => {
  addCommentVisible.value = false;
  saveFrom.value = { comments: '' };
  rating.value = 0;
};

// 提交评论
const addComment = () => {
  if (loading.value) return;

  if (!rating.value) {
    ElMessage.warning("请选择评分");
    return;
  }

  if (!saveFrom.value.comments.trim()) {
    ElMessage.warning("评论内容不能为空");
    return;
  }

  loading.value = true;

  const data = qs.stringify({
    userId: props.userId,
    filmId: props.filmId,
    content: saveFrom.value.comments,
    rating: rating.value,
  });

  axios.post(BASE_URL + '/v1/comments/addComments', data)
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success("评论添加成功");
          getComments(); // 刷新评论列表
          cancel(); // 关闭弹窗并重置表单
        } else {
          ElMessage.error(response.data.msg);
        }
      })
      .finally(() => {
        loading.value = false;
      });
};
</script>

<style scoped>
.add-comment {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.btn {
  width: 150px;
  height: 40px;
  background-color: #671523;
  border-radius: 10px;
  color: #fff;
  font-size: 16px;
  font-weight: bold;
  border: transparent;
}

.comment-item {
  border-bottom: 1px solid #ddd;
  padding: 10px 0;
}

.comment-item p {
  margin-top: 5px;
  padding: 0;
  font-size: 16px;
  color: #fff;
}

.comment-content {
  margin-top: 10px;
  font-size: 16px;
  color: #fff;
  line-height: 1.5;
  margin-left: 40px;
}
</style>